#include "LevelLoader.hpp"

#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <math.h>

LevelLoader::LevelLoader(){

}

void LevelLoader::setLevelTile(const std::string& levelName, int level, int angle, int id)
{
    worlds[levelName].setTile(level,angle,id);
}

bool LevelLoader::load(const std::string& filename){

    std::ifstream file(filename.c_str(), std::ios::in);  // on ouvre
    std::vector < std::vector < int > > level;
    std::vector < int > floor;

    if(file)
    {
        while(!file.eof())
        {
            std::string line;
            std::getline(file,line);    // Read the level line

            // std::cout << "Read line: " <<

            std::stringstream lineReader(line); // Handle the line
            unsigned int counter = 0;
            while ( !lineReader.eof() )
            {
                int id = -1;
                lineReader >> id;
                if ( id == -1 )
                {
                    // std::cerr << "Fail to read id from file" << std::endl;
                    break;
                }
                floor.push_back(id);

                counter++;
            }

            std::cout << "Counter: " << counter << std::endl;

            if ( floor.size() != 0 )
            {
                level.push_back(floor);
            }
            floor.clear();
        }

        worlds[filename] = Level(level);
        level.clear();

        file.close();
    }
    else
    {
        // We create a map
        std::vector< std::vector< int > > world;
        for ( unsigned int i = 0 ; i < 7 ; i ++ )
        {
            std::vector<int> floor;
            for ( unsigned int j = 0 ; j < powf(2,8-i) ; j++ )
            {
                floor.push_back(1);
            }

            world.push_back(floor);
        }

        worlds[filename] = Level(world);

        return true;
    }

    return true;
}

const Level& LevelLoader::getLevel(const std::string& name)const
{
    std::map<std::string , Level>::const_iterator itElem = worlds.find(name);
    if ( itElem == worlds.end() )
    {
        std::cerr << "Level not found with '" << name << "'" << std::endl;
    }

    return itElem->second;
}

void LevelLoader::print(){
    std::map<std::string , Level >::iterator it = worlds.begin();

    std::cout << "PRINT LEVELS" <<std::endl;

    while(it!=worlds.end())
    {
        std::cout<< it->first <<"\n";

        it->second.print();

        it++;
    }
}
